﻿Imports Co9320.NamaAlert.Extension
Imports System.ComponentModel
Imports Co9320.NamaAlert.Model

Public Class PluginFinder
    Implements ISystemMessageSender

#Region "Events"

    Public Event PluginsFound As EventHandler(Of PluginsFoundEventArgs)
    Protected Overridable Sub OnPluginsFound(ByVal e As PluginsFoundEventArgs)
        RaiseEvent PluginsFound(Me, e)
    End Sub

    Public Event SendSystemMessage(ByVal sender As Object, ByVal e As Model.SystemMessageEventArgs) Implements Model.ISystemMessageSender.SendSystemMessage
    Protected Overridable Sub OnSendSystemMessage(ByVal e As SystemMessageEventArgs)
        RaiseEvent SendSystemMessage(Me, e)
    End Sub

#End Region


    Public Function FindPlugins(ByVal path As String) As IList(Of PluginFileInfo)

        Dim list = New List(Of PluginFileInfo)

        If Not System.IO.Directory.Exists(path) Then
            Return list

        End If

        Dim files = System.IO.Directory.GetFiles(path, "*.dll")

        For Each file In files

            Try
                Dim asm = System.Reflection.Assembly.LoadFrom(file)
                For Each t In asm.GetTypes
                    If t.IsClass AndAlso t.IsPublic AndAlso Not t.IsAbstract AndAlso _
                       t.GetInterface("IPlugin") IsNot Nothing AndAlso _
                       t.GetCustomAttributes(GetType(PluginAttribute), True).Count > 0 Then

                        Dim attribute = DirectCast(t.GetCustomAttributes(GetType(PluginAttribute), True).First, PluginAttribute)
                        list.Add(New PluginFileInfo(file, attribute.Guid))
                        Continue For
                    End If
                Next

            Catch ex As Exception
                OnSendSystemMessage(New SystemMessageEventArgs(SystemMessageKind.Verbose, "プラグイン探索: " & ex.Message))
            End Try
        Next

        Return list
    End Function

    Private Sub FindPlugins(ByVal obj As Object)
        Dim path = DirectCast(obj, String)
        Dim list = FindPlugins(path)

        Dim args = New PluginsFoundEventArgs
        If args.Info.Count > 0 Then
            OnPluginsFound(args)
        End If

    End Sub

    Public Sub FindPluginsAsync(ByVal path As String)
        Dim thread = New System.Threading.Thread(AddressOf FindPlugins)
        thread.Start(path)
    End Sub

End Class
